package com.xyzwps.server.paimon.graphql.scalar

import com.xyzwps.server.paimon.value.UserId
import graphql.GraphQLContext
import graphql.execution.CoercedVariables
import graphql.language.IntValue
import graphql.language.NullValue
import graphql.language.StringValue
import graphql.language.Value
import graphql.schema.Coercing
import graphql.schema.GraphQLScalarType
import java.util.Locale


internal object UserIdCoercing : Coercing<UserId, String> {
    override fun serialize(dataFetcherResult: Any, ctx: GraphQLContext, locale: Locale): String =
        when (dataFetcherResult) {
            is UserId -> dataFetcherResult.value.toString()
            else -> throw IllegalArgumentException("Invalid user id")
        }

    override fun parseValue(input: Any, ctx: GraphQLContext, locale: Locale): UserId =
        when (input) {
            is UserId -> input
            is String -> UserId(input.toLong())
            is Number -> UserId(input.toLong())
            else -> throw IllegalArgumentException("Invalid user id")
        }

    override fun parseLiteral(input: Value<*>, vars: CoercedVariables, ctx: GraphQLContext, locale: Locale): UserId? =
        when (input) {
            is StringValue -> UserId(input.value.toLong())
            is IntValue -> UserId(input.value.toLong())
            is NullValue -> null
            else -> throw IllegalArgumentException("Invalid phone number")
        }
}


val USER_ID_SCALAR: GraphQLScalarType = GraphQLScalarType.newScalar()
    .name("UserId")
    .description("User id")
    .coercing(UserIdCoercing)
    .build()
